package com.fc.redap.utils;

import com.fc.redap.helper.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class HttpContextUtils {
	private static final Logger log = LoggerFactory.getLogger(HttpContextUtils.class);

	private static final String ENCODING = "UTF-8";
	private static final String CONTENT_TYPE = "application/json";

	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static boolean isAjax(ServletRequest request){
		return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request)
				.getHeader("X-Requested-With"));
	}

	public static boolean isAjax(){
		ServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request)
				.getHeader("X-Requested-With"));
	}

	public static void sendJSON(HttpServletResponse response, Object obj) {
		response.setContentType(CONTENT_TYPE);
		response.setCharacterEncoding(ENCODING);
		PrintWriter outResponse = null;

		try {
			outResponse = response.getWriter();
			outResponse.print(JsonUtils.toJson(obj));
			outResponse.flush();
		} catch (IOException e) {
			log.error("json utils exception :" + e);
		} finally {
			if (outResponse != null) {
				outResponse.close();
			}
		}
	}
}
